import React, { useState } from 'react';
import { useQuery, useAction, getMessages, addMessage } from 'wasp/client/operations';
import { useParams } from 'wasp/client/router';

const ChatPage = () => {
  const { chatId } = useParams();
  const { data: messages, isLoading, error } = useQuery(getMessages, { chatId });
  const addMessageFn = useAction(addMessage);
  const [newMessageContent, setNewMessageContent] = useState('');
  const [sender, setSender] = useState('');

  if (isLoading) return 'Loading...';
  if (error) return 'Error: ' + error;

  const handleSendMessage = () => {
    if (newMessageContent.trim() !== '') {
      addMessageFn({ chatId, content: newMessageContent, sender });
      setNewMessageContent('');
    }
  };

  return (
    <div className="p-4">
      <div className="mb-4">
        {messages.map((message) => (
          <div key={message.id} className="mb-2 p-2 border rounded">
            <strong>{message.sender}:</strong> {message.content}
          </div>
        ))}
      </div>
      <div className="flex gap-x-2">
        <input
          type="text"
          placeholder="Sender"
          className="px-2 py-1 border rounded"
          value={sender}
          onChange={(e) => setSender(e.target.value)}
        />
        <input
          type="text"
          placeholder="Type a message"
          className="flex-grow px-2 py-1 border rounded"
          value={newMessageContent}
          onChange={(e) => setNewMessageContent(e.target.value)}
        />
        <button
          onClick={handleSendMessage}
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-1 px-4 rounded"
        >
          Send
        </button>
      </div>
    </div>
  );
};

export default ChatPage;
